package lt.hsu.auth;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class SwaggerInfoCollectorRunner implements CommandLineRunner {

    @Resource
    private RequestMappingHandlerMapping handlerMapping;

//    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public void run(String... args) {
        List<EndpointInfo> endpointsInfo = new ArrayList<>();

        // 获取所有的URL和方法的映射
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo mappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();

            // 获取URL
            String urlPattern = mappingInfo.getPatternsCondition().getPatterns().iterator().next();

            // 获取Swagger注解信息
            Operation operationAnnotation = handlerMethod.getMethodAnnotation(Operation.class);
            SecurityScheme schemeAnnotation = handlerMethod.getBeanType().getAnnotation(SecurityScheme.class);

            String description = operationAnnotation != null ? operationAnnotation.description() : "";
            String roles = schemeAnnotation != null ? schemeAnnotation.name() : "";

            // 获取HTTP方法
            Set<RequestMethod> methods = mappingInfo.getMethodsCondition().getMethods();
            String httpMethod = methods.isEmpty() ? "ANY" : methods.iterator().next().name();


            // 构建EndpointInfo对象
            EndpointInfo endpointInfo = new EndpointInfo(urlPattern, description, roles, httpMethod);
            endpointsInfo.add(endpointInfo);
        }

        // 打印或处理收集到的endpointsInfo信息
//        redisTemplate.convertAndSend("endpointsInfo", endpointsInfo);
    }

    @Data
    @AllArgsConstructor
    static class EndpointInfo {
        private String url;
        private String name;
        private String role;
        private String httpMethod;
    }
}
